
var searchURL;
var clusterString;
var jsonClusterDetails;
var xmlHttp;

var jsonSemanticCluster;
var jsonSiteCluster;
var jsonTimeCluster;

document.write("<script type='text/javascript' src='script/jquery.cookie.js'></script>"); 
document.write("<script type='text/javascript' src='script/jgcharts.js'></script>"); 

function createXMLHttpRequest()
{
	if(xmlHttp == null)
	{
	 	if(window.ActiveXObject)
	 	{
	 	 	xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	 	}
	 	else if(window.XMLHttpRequest)
	 	{
	  		xmlHttp=new XMLHttpRequest();
	 	}
	}
}
/*获取结果*/
function getDetails(url)
{
	
	searchURL = url;
	//$.get("servlet/GetTimeCluster",url,showTimeCluster);
	$.get("servlet/GetRelativeSearch",url,showRelativeSearch);
	$.get("servlet/GetDetails",url,showDetailsAndGetSpaceCluster);
}

/*显示结果*/
function showDetails(data)
{
	var details = eval('(('+data+'))');
	var totalHits = details.TotalHits;	
    if (totalHits == 0) {
        $("#detailsShow").html("抱歉，没有找到与你的查询相关的网页。 ");
    }else
    {
    	var detailsShow = "<table>";			//显示结果html文本
        var pageIndexShow = "";					//显示页码的html文本
        var costTimeShow = "";					//显示结果总数和时间开销的html文本

        var detailsresult = details.Details;	//获取结果
        var costTime = details.CostTime;		//获取时间开销
        var pageIndex = details.PageIndex;		//页码
        	
        
        costTimeShow = "<font size='2px'>获得约&nbsp;"+totalHits+"&nbsp;个结果，用时&nbsp;"+costTime+"&nbsp;毫秒</font>"
        //显示结果总数和时间开销
       	$("#costTimeShow").html(costTimeShow);
       	//开始显示结果
       	//var length = detailsresult.length;
       	var start = details.Start;
       	var end = details.End;
       	var i=start;
       	while(i<end)
        {
        	var detail = detailsresult[i];
        	var title = detail.Title;
        	var url = detail.URL;
        	var showUrl = (url.length>60)?url.substring(0,56)+ "...":url;
        	var pageCover = detail.PageCover;
        	var summary = detail.Summary;
        	var workerName = detail.WorkerName;
        	var oworkerName = detail.OWorkerName;
        	var siteStyle = detail.SiteStyle;
        	var ositeStyle = detail.OSiteStyle;
        	var date = detail.Date;
        	var moreDetails = detail.MoreDetails;
        	var isSafe = detail.IsSafe.toLowerCase();
        	var pageCoverImg ="";
			if(pageCover != "")
			{
				pageCoverImg = "<img src=\""+pageCover+"\" style=\"height:90px;width:140px\"/>";
			}
	
			var hustTest = "";
			if(isSafe !="safe")
			{
				hustTest = "<a href='http://218.199.102.42:8080/sec6/detail.jsp?searchtask="+url+"' target='_blank'><img src='images/notsafe.jpg' style='height: 15; width: 15; border: 0'></a>";
			}
			else {
				hustTest = "<img src='images/safe.jpg' style='height: 15; width: 15'>";
			}
			
			var clickData = "javascript:clickURL('"+url+"','"+oworkerName+"','"+ositeStyle+"')";
			detailsShow += "<tr><td id='detailTitle'><a href='"+url+"' target='_blank' onClick=\""+clickData+"\"><font size='4'>"+title+"</font></a></td>";
			
			detailsShow += "<td rowspan='4' valign='top'>"+pageCoverImg+"</td></tr>";

			detailsShow += "<tr><td style='font-size: 13'>" +
					"来源：<font color='7B828C'>"+workerName+"</font>&nbsp;&nbsp;" +
					"资源属性：<font color='7B828C'>"+siteStyle+"</font>&nbsp;&nbsp;" +
					"更新时间：<font color='7B828C'>"+date+"</font>&nbsp;&nbsp;" +
					hustTest +
					"</td></tr>";
			detailsShow += "<tr valign='top'><td valign='top'><font size='2'>"+summary+"</font><br>" +
					"<font size=2 color='#4E876A'>"+showUrl+"</font></td></tr>";
			if(moreDetails != null)
			{
				var moreData = "javascript:showMoreDetail('"+detail.SimURL+"',this)";
				detailsShow += "<tr><td ><span class='moreDetail' onClick=\""+moreData+"\"><img src='images/plus.gif' style='width:12px;height:12px'/>显示来自 "+detail.SimURL+" 的更多搜索结果</span><div style='display:none'>"+moreDetails+"</div></td></tr>";
			}
			detailsShow += "<tr><td></td></tr>";
        	i++;
        }
       detailsShow += "</table>";
       //设置结果
       $("#detailsShow").html(detailsShow);
       //设置页码
       $("#pageIndex").html(pageIndex);
       showSiteHitChart(details.SiteHit);
    }
}

function showSiteHitChart(siteHit)
{
	var datas = siteHit.Datas;
	var labels = siteHit.Labels;
	var num = siteHit.Num;
	var tcolor = siteHit.Colors;
	var tsize = siteHit.Size;
	if(num == 0)
		return;
	var api = new jGCharts.Api();
	$("#siteHitBar").html("<Font size=4><strong>各节点命中数</strong> </Font><br>");
	
	jQuery('<img>').attr('src', api.make(
	{
		data : datas,
		axis_labels : labels,
		
		type : 'bhs',
		grid : true,
		bar_width   : 20, 
		bar_spacing : 10,
		size : tsize
	}
	)).appendTo("#siteHitBar");
}

/*显示时间聚类的结果*/
function showTimeCluster(data)
{
	//设置时间聚类结果
     $("#timeCluster").html(data);
}

/*显示搜索结果，并获取控件聚类结果*/
function showDetailsAndGetSpaceCluster(data)
{
	//获取控件聚类结果
	//$.get("servlet/GetSpaceCluster",searchURL,showSpaceCluster);
	
	//显示结果
	showDetails(data);
	
	updatePieChart();
	$.get("servlet/GetCluster",searchURL,showCluster);
	
}

function updatePieChart()
{
	var img = "<img src='servlet/GetPieChart' id='myImg' style='height:140;width=120'>";
	$("#v4v6PieChart").html(img);
}

/*显示空间聚类结果*/
function showSpaceCluster(data)
{
	var details = eval('(('+data+'))');
	var hasCluster = details.HasCluster;
	clusterString = details.ClusterString;
	//用全局变量记录聚类的结果
	jsonClusterDetails = details.JSONClusterDetails;
	//设置空间聚类结果
	$("#spaceCluster").html(clusterString);
}

/*显示空间聚类结果*/
function showCluster(data)
{
	var details = eval('(('+data+'))');
	var semanticCluster = details.SemanticCluster;
	var siteCluster = details.SiteCluster;
	var timeCluster = details.TimeCluster;
	
	var semanticLabel = semanticCluster.Label;
	var semanticResult = semanticCluster.Details;
	var siteLabel = siteCluster.Label;
	var siteResult = siteCluster.Details;
	var timeLabel = timeCluster.Label;
	var timeResult = timeCluster.Details;
	
	$("#timeCluster").html(timeLabel);
	$("#spaceCluster").html(semanticLabel);
	$("#siteCluster").html(siteLabel);
	
	jsonSemanticCluster = semanticResult;
  	jsonSiteCluster = siteResult;
	jsonTimeCluster = timeResult;
	
	//setClusterCookie(semanticLabel,semanticResult,siteLabel,siteResult,timeLabel,timeResult);
}

/*清空聚类结果cookie*/
function clearClusterCookie()
{
	$.cookie('semanticLabel', null); 
	$.cookie('semanticResult', null); 
	$.cookie('siteLabel', null); 
	$.cookie('siteResult', null); 
	$.cookie('timeLabel', null); 
	$.cookie('timeResult', null); 
}

/*设置聚类结果cookie*/
function setClusterCookie(semanticLabel,semanticResult,siteLabel,siteResult,timeLabel,timeResult)
{
	$.cookie('semanticLabel', semanticLabel, {expires: 30}); 
	$.cookie('semanticResult', semanticResult, {expires: 30}); 
	$.cookie('siteLabel', siteLabel, {expires: 30}); 
	$.cookie('siteResult', siteResult, {expires: 30}); 
	$.cookie('timeLabel', timeLabel, {expires: 30}); 
	$.cookie('timeResult', timeResult, {expires: 30}); 
}

/*显示相关搜索结果*/
function showRelativeSearch(data)
{
	//设置相关搜索结果
     $("#relativeSearch").html(data);
}

/*点击控件聚类节点时，显示聚类的结果*/
function showSpacePageDetails(ci,page,perPage)
{
	//清空结果总数和时间开销
    $("#costTimeShow").html("");
    $("#pageIndex").html("");
	if(jsonClusterDetails == null || ci>=jsonClusterDetails.length)
	{
		 $("#detailsShow").html("抱歉，没有相关的聚类结果!");
		return;
	}
	/*获取到第ci个聚类的结果*/
	var data = jsonClusterDetails[ci];
	/*获取结果总数，这个总数和实际的聚类结果的数目相等*/
	var totalHits = data.TotalHits;	
    if (totalHits == 0) {
        $("#detailsShow").html("抱歉，没有相关的聚类结果!");
    }else
    {
    	var detailsShow = "<table>";			/*显示结果html文本*/
        var pageIndexShow = "";					/*显示页码的html文本*/

        var detailsresult = data.Details;	/*获取结果*/
        	
        
       	/*开始显示结果*/
       	var length = detailsresult.length;
       	var start = page*perPage;
       	var end = Math.min(start + perPage,length);
       	var i=start;
       	while(i<end)
        {
        	var detail = detailsresult[i];
        	var title = detail.Title;
        	var url = detail.URL;
        	var showUrl = (url.length>60)?url.substring(0,56)+ "...":url;
        	var pageCover = detail.PageCover;
        	var summary = detail.Summary;
        	var workerName = detail.WorkerName;
        	var oworkerName = detail.OWorkerName;
        	var siteStyle = detail.SiteStyle;
        	var ositeStyle = detail.OSiteStyle;
        	var date = detail.Date;
        	var isSafe = detail.IsSafe.toLowerCase();
        	var pageCoverImg ="";
			if(pageCover != "")
			{
				pageCoverImg = "<img src=\""+pageCover+"\" style=\"height:90px;width:140px\"/>";
			}
			
			var safeImage = "images/safe.jpg";
			if(isSafe !="safe")
				safeImage = "images/notsafe.jpg";
				
			var clickData = "javascript:clickURL('"+url+"','"+oworkerName+"','"+ositeStyle+"')";
			detailsShow += "<tr><td id='detailTitle'><a href='"+url+"' target='_blank' onClick=\""+clickData+"\"><font size='4'>"+title+"</font></a></td>";
			detailsShow += "<td rowspan='3' valign='top'>"+pageCoverImg+"</td></tr>";
			detailsShow += "<tr><td style='font-size: 13'>" +
					"来源：<font color='7B828C'>"+workerName+"</font>&nbsp;&nbsp;" +
					"资源属性：<font color='7B828C'>"+siteStyle+"</font>&nbsp;&nbsp;" +
					"更新时间：<font color='7B828C'>"+date+"</font>&nbsp;&nbsp;" +
					"<img src="+safeImage+" style='height: 15; width: 15'>" +
					"</td></tr>";
			detailsShow += "<tr valign='top'><td valign='top'><font size='2'>"+summary+"</font><br>" +
					"<font size=3 color='#4E876A'>"+showUrl+"</font><br><br></td></tr>";
        	i=i+1;
        }
       detailsShow += "</table>";
       /*设置结果*/
       $("#detailsShow").html(detailsShow);
       /*更新页码索引*/
       var maxPage = (length+perPage-1)/perPage;
       updateClusterPageIndex(ci,page+1,perPage,Math.floor(maxPage),10);
    }
}

/*点击 空间聚类节点时，显示聚类的结果*/
function showSemanticPageDetails(ci,page,perPage)
{
	var results = jsonSemanticCluster;
	showClusterPage(0,results,ci,page,perPage);
}

/*点击时间聚类节点时，显示聚类的结果*/
function showTimePageDetails(ci,page,perPage)
{
	var results = jsonTimeCluster;
	showClusterPage(1,results,ci,page,perPage);
}

/*点击站点聚类节点时，显示聚类的结果*/
function showSitePageDetails(ci,page,perPage)
{
	var results = jsonSiteCluster;
	showClusterPage(2,results,ci,page,perPage);
}

function showClusterPage(type,datas,ci,page,perPage)
{
	//清空结果总数和时间开销
    $("#costTimeShow").html("");
    $("#pageIndex").html("");
	if(datas == null || ci>=datas.length)
	{
		 $("#detailsShow").html("抱歉，没有相关的聚类结果!");
		return;
	}
	/*获取到第ci个聚类的结果*/
	var data = datas[ci];
	/*获取结果总数，这个总数和实际的聚类结果的数目相等*/
	var totalHits = data.TotalHits;	
    if (totalHits == 0) {
        $("#detailsShow").html("抱歉，没有相关的聚类结果!");
    }else
    {
    	var detailsShow = "<table>";			/*显示结果html文本*/
        var pageIndexShow = "";					/*显示页码的html文本*/

        var detailsresult = data.Details;	/*获取结果*/
        	
        
       	/*开始显示结果*/
       	var length = detailsresult.length;
       	var start = page*perPage;
       	var end = Math.min(start + perPage,length);
       	var i=start;
       	while(i<end)
        {
        	var detail = detailsresult[i];
        	var title = detail.Title;
        	var url = detail.URL;
        	var showUrl = (url.length>60)?url.substring(0,56)+ "...":url;
        	var pageCover = detail.PageCover;
        	var summary = detail.Summary;
        	var workerName = detail.WorkerName;
        	var oworkerName = detail.OWorkerName;
        	var siteStyle = detail.SiteStyle;
        	var ositeStyle = detail.OSiteStyle;
        	var date = detail.Date;
        	var isSafe = detail.IsSafe.toLowerCase();
        	var pageCoverImg ="";
			if(pageCover != "")
			{
				pageCoverImg = "<img src=\""+pageCover+"\" style=\"height:90px;width:140px\"/>";
			}
			
			var safeImage = "images/safe.jpg";
			if(isSafe !="safe")
				safeImage = "images/notsafe.jpg";
				
			var clickData = "javascript:clickURL('"+url+"','"+oworkerName+"','"+ositeStyle+"')";
			detailsShow += "<tr><td id='detailTitle'><a href='"+url+"' target='_blank' onClick=\""+clickData+"\"><font size='4'>"+title+"</font></a></td>";
			detailsShow += "<td rowspan='3' valign='top'>"+pageCoverImg+"</td></tr>";
			detailsShow += "<tr><td style='font-size: 13'>" +
					"来源：<font color='7B828C'>"+workerName+"</font>&nbsp;&nbsp;" +
					"资源属性：<font color='7B828C'>"+siteStyle+"</font>&nbsp;&nbsp;" +
					"更新时间：<font color='7B828C'>"+date+"</font>&nbsp;&nbsp;" +
					"<img src="+safeImage+" style='height: 15; width: 15'>" +
					"</td></tr>";
			detailsShow += "<tr valign='top'><td valign='top'><font size='2'>"+summary+"</font><br>" +
					"<font size=3 color='#4E876A'>"+showUrl+"</font><br><br></td></tr>";
        	i=i+1;
        }
       detailsShow += "</table>";
       /*设置结果*/
       $("#detailsShow").html(detailsShow);
       /*更新页码索引*/
       var maxPage = (length+perPage-1)/perPage;
       updateClusterPageIndex1(type,ci,page+1,perPage,Math.floor(maxPage),10);
	}
}

/*在点击聚类的页面索引时，更新页码显示*/
/**
 * ci：聚类结果的下标
 * page：点击的页码
 * perPage：每页显示的结果数目
 * maxPageNum：总共的页数
 * showPageNum：显示的页码的数目
 */
function updateClusterPageIndex(ci,page,perPage,maxPageNum,showPageNum)
{
	if(maxPageNum==1)
			return "";
	var pageIndex = "<table><tr>";
	var start = page - Math.floor(showPageNum/2);
	start = (start>0)?start:1;
	var end = start + showPageNum-1;
	if(end>maxPageNum)
	{
		end = maxPageNum;
		start = maxPageNum - showPageNum;
		start = (start>0)?start:1;
	}
	var i;
	if(page>1)
	{
		var href = "javascript:showSpacePageDetails("+ci+","+(page-2)+","+perPage+")";
		pageIndex += "<td><a href=\""+href+"\">上一页</a>&nbsp;</td>";
	}
	for(i=start;i<=end;i=i+1)
	{
		if(i == page)
		{
			pageIndex += "<td>"+i+"&nbsp;</td>";
		}
		else {
			var href = "javascript:showSpacePageDetails("+ci+","+(i-1)+","+perPage+")";
			pageIndex += "<td><a href=\""+href+"\">["+i+"]</a>&nbsp;</td>";
		}
	}
	if(page<maxPageNum)
	{
		var href = "javascript:showSpacePageDetails("+ci+","+page+","+perPage+")";
		pageIndex += "<td><a href=\""+href+"\">下一页</a>&nbsp;</td>";
	}
	pageIndex += "</tr></table>";
	//设置页码
    $("#pageIndex").html(pageIndex);
}

/*在点击聚类的页面索引时，更新页码显示*/
/**
 * type: 类别（语义or时间or来源站点）
 * ci：聚类结果的下标
 * page：点击的页码
 * perPage：每页显示的结果数目
 * maxPageNum：总共的页数
 * showPageNum：显示的页码的数目
 */
function updateClusterPageIndex1(type,ci,page,perPage,maxPageNum,showPageNum)
{
	if(maxPageNum==1)
			return "";
	var pageIndex = "<table><tr>";
	var start = page - Math.floor(showPageNum/2);
	start = (start>0)?start:1;
	var end = start + showPageNum-1;
	if(end>maxPageNum)
	{
		end = maxPageNum;
		start = maxPageNum - showPageNum;
		start = (start>0)?start:1;
	}
	var i
	var func = "";
	if(type==0)
	{
		func = "javascript:showSemanticPageDetails(";
	}else if(type ==1)
	{
		func = "javascript:showTimePageDetails(";
	}else if(type == 2)
	{
		func = "javascript:showSitePageDetails(";
	}
	
	if(page>1)
	{
		var href = func+ci+","+(page-2)+","+perPage+")";
		pageIndex += "<td><a href=\""+href+"\">上一页</a>&nbsp;</td>";
	}
	for(i=start;i<=end;i=i+1)
	{
		if(i == page)
		{
			pageIndex += "<td>"+i+"&nbsp;</td>";
		}
		else {
			var href = func+ci+","+(i-1)+","+perPage+")";
			pageIndex += "<td><a href=\""+href+"\">["+i+"]</a>&nbsp;</td>";
		}
	}
	if(page<maxPageNum)
	{
		var href = func+ci+","+page+","+perPage+")";
		pageIndex += "<td><a href=\""+href+"\">下一页</a>&nbsp;</td>";
	}
	pageIndex += "</tr></table>";
	//设置页码
    $("#pageIndex").html(pageIndex);
}

/*相关搜索*/
function relativeSearch(perPage,text)
{
	//对界面进行一下初始化
	$("#spaceCluster").html("<img src='images/loading.gif''>");
	$("#relativeSearch").html("<img src='images/loading.gif''>");
	$("#timeCluster").html("<img src='images/loading.gif''>");
	 $("#detailsShow").html("<img src='images/loading.gif''>搜索中...");
	 $("#pageIndex").html("");
	 $("#costTimeShow").html("");
	
	var url = "page=0";
	url += "&perPage="+perPage;
	url += "&searchText="+encodeURI(text);
	$.get("servlet/GetDetails",url,showDetailsAndGetSpaceCluster);
	$.get("servlet/GetRelativeSearch",url,showRelativeSearch);
	$.get("servlet/GetTimeCluster",url,showTimeCluster);
	//更新窗口标题和输入框文字
	updateTextAndTitle(text);
	//更新时间聚类结果
	updateTimeCluster(perPage,text);
}
/*更新输出框里面的文字和窗口标题*/
function updateTextAndTitle(text)
{
	$("#searchtext1").val(text);
	$("#searchtext2").val(text);
	document.title = text+"  下一代互联网分布式搜索引擎平台"; 
}

/*更新时间聚类的显示*/
function updateTimeCluster(perPage,text)
{
	var url = "perPage="+perPage;
	url += "&searchText="+encodeURI(text);
	$.get("servlet/GetTimeCluster",url,showTimeCluster);
}

/*时间聚类搜索*/
function timeSearch(perPage,text,span,flag)
{
	//对界面进行一下初始化
	$("#spaceCluster").html("<img src='images/loading.gif''>");
	$("#relativeSearch").html("<img src='images/loading.gif''>");
	$("#detailsShow").html("<img src='images/loading.gif''>搜索中...");
	$("#pageIndex").html("");
	$("#costTimeShow").html("");
	 
	var url = "page=0";
	url += "&perPage="+perPage;
	url += "&searchText="+encodeURI(text);
	url += "&flag="+flag;
	url += "&span="+span;
	$.get("servlet/GetDetails",url,showDetailsAndGetSpaceCluster);
	$.get("servlet/GetRelativeSearch",url,showRelativeSearch);
}


function showMoreDetail(url,data)
{
	var moreDiv = data.nextSibling;
	if(moreDiv.style.display == "none")
	{
		data.innerHTML = "<img src='images/reduce.gif' style='width:12px;height:12px'/>隐藏来自 "+url+" 的更多搜索结果";
		moreDiv.style.display = "block";
	}
	else 
	{
		data.innerHTML = "<img src='images/plus.gif' style='width:12px;height:12px'/>显示来自 "+url+" 的更多搜索结果";
		moreDiv.style.display = "none";
	}
}

function showSourceStat(data)
{
	if (GBrowserIsCompatible()) 
	{
		 var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(37.5, 103.95), 4);
    map.disableDragging();
    map.disableDoubleClickZoom();
    
    // 为所有标记创建指定阴影、图标尺寸灯的基础图标
    var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.cn/mapfiles/shadow50.png";
 	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
    //读取每个城市的值
 	 	var sourceStat = eval('(('+data+'))').CitySource;
 	 	var length = sourceStat.length;
 	 	var i=0;
 	 	while(i<length)
 	 	{
 	 		var city = sourceStat[i];
 	 		var name = city.Name;
 	 		var jindu = city.Jindu;
 	 		var weidu = city.Weidu;
 	 		var v4 = city.V4;
 	 		var v6 = city.V6;
 	 		var v46 = city.V46;
 	 		var latlng = new GLatLng(parseFloat(jindu),parseFloat(weidu));
 	 		map.addOverlay(createMarker(baseIcon,name,v4,v6,v46,latlng,i));
 	 		i++;
 	 	}
 	}
}

function createMarker(baseIcon,name,v4,v6,v46,point,index)
{
	var v4letter = "<tr><td> IPv4资源数 </td><td> <b>" + v4 + "</b></td></tr>";
  	var v6letter = "<tr><td>纯IPv6资源数 </td><td><b>"+ v6 + "</b></td></tr>";
  	var v46letter = "<tr><td>双栈资源数 </td><td><b>"+ v46 +"</b></td></tr>";
  	var letteredIcon = new GIcon(baseIcon);
 	letteredIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/marker" + (index+1) + ".png";
 	 // 设置 GMarkerOptions 对象
 	markerOptions = {icon:letteredIcon};
  	var marker = new GMarker(point, markerOptions);
 	var show = "<table><tr><td>"+name+"</td><td></td></tr>"+v4letter+v6letter+v46letter;

  	GEvent.addListener(marker, "click", function(){
   		 marker.openInfoWindowHtml(show);
  	});
  	return marker;
}